<?php
declare (strict_types=1);

namespace app\api\controller\v1;

use app\api\model\v1\ActivityTagAccess;
use app\api\model\v1\AdminLog;
use app\api\model\v1\Admins;
use app\api\model\v1\Characteristic;
use app\api\model\v1\Community;
use app\api\model\v1\Difficult;
use app\api\model\v1\Examine;
use app\api\model\v1\GatherCompany;
use app\api\model\v1\InspectActivity;
use app\api\model\v1\InspectActivityTag;
use app\api\model\v1\LeaderDoc;
use app\api\model\v1\PutOnRecord;
use app\api\model\v1\TemporaryAlbum;
use app\api\model\v1\Voluntary;
use app\BaseController;
use think\facade\Db;
use think\facade\Env;
use think\helper\Str;
use think\Request;

//新需求---功能
class Demand extends BaseController
{

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/11 11:12
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 数据源
     */
    public function getLeaderDocList()
    {
        $limit = $this->request->param('limit', 10);
        $ly = $this->request->param('ly', 0);
        $draft = $this->request->param('draft', 1);
        if (intval($draft) === 2) {
            $draft_one = 1;
        } else {
            $draft_one = 2;
        }
        $map = [];
        if (intval($ly) === 0) {
            //获取整改管理员和超级管理员
            if (!$this->auth->isSuperAdmin($this->request->wx_id)) {
                $group_id_arr = $this->auth->getGroups($this->request->wx_id)->toArray(); //获取当前角色的id
                $new_string = '';
                foreach ($group_id_arr as $k => $v) {
                    $new_string .= $v['name'] . ',';
                }
                $new_string = rtrim($new_string, ',');
                if (Str::contains($new_string, '整改管理员')) {
                    $childrenList = $this->search->getChildrenIds($this->request->wx_unit_id, true);
                    $map[] = array('unit_id', 'in', $childrenList);
                } else {
                    $map[] = ['user_id', '=', $this->request->wx_id];
                }
            }
        }
        $map[] = ['draft', '=', $draft_one];
        $res = LeaderDoc::with(['admin', 'unit' => ['community']])->where($map)->order('create_time desc')->paginate($limit)->each(function ($item, $key) {
            if (empty($item['unit'])) {
                $item['unit_title'] = '未知单位';
                $item['community_title'] = '未知社区';
            } else {
                $item['unit_title'] = $item['unit']['title'];
                $item['community_title'] = $item['unit']['community']['community_title'] ?? '未知社区';
            }

            if ($item['path']) {
                $path_arr = json_decode($item['path'], true);
                $item['path_arr'] = reset($path_arr)['url'] ?? Env::get('IMG_HTTP.img_http') . 'logo.png';
            } else {
                $item['path_arr'] = Env::get('IMG_HTTP.img_http') . 'logo.png';
            }
            return $item;

        });
        return $this->response($res);
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/11 11:02
     * @return \think\response\Json
     * 保存领导调度
     */
    public function saveLeaderDoc()
    {
        $data = $this->request->param();
        $ly = $this->request->param('ly', 0);
        $leader_id = $this->request->param('id', 0);
        if (is_array($data['path'])) {
            foreach ($data['path'] as $key => $v) {
                $data['path'][$key]['thumb'] = $v['url'];
            }
            $data['path'] = json_encode($data['path'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); //不转义
        }
        if (intval($ly) === 0) {
            $data['user_id'] = $this->request->wx_id ?? $this->request->uid;
            $data['username'] = $this->request->wx_user_name ?? $this->request->username;
            $data['unit_id'] = $this->request->wx_unit_id ?? $this->request->unit_id;
        }
        if (intval($leader_id) === 0) {
            LeaderDoc::create($data);
        } else {
            $leader = LeaderDoc::find($leader_id);
            $leader->update($data);
        }

        //操作日志
        AdminLog::record('保存领导调度', json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), $this->request->wx_id ?? $this->request->uid, $this->request->wx_user_name ?? $this->request->username);
        return $this->response();
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/11 11:26
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除领导调度
     */
    public function delLeader()
    {
        $data = $this->request->param();

        $res = LeaderDoc::find($data['id']);
        if (is_null($res)) {
            return $this->response(403, '未找到该信息');
        }
        $res->delete();
        AdminLog::record('删除领导调度', $data, $this->request->wx_id, $this->request->wx_user_name);
        return $this->response();
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/11 11:31
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 领导调度详情
     */
    public function leaderDetail()
    {
        $date = date('Y-m-d');  //当前日期
        $first = 1; //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
        $w = date('w', strtotime($date));  //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
        $now_start = date('Y-m-d', strtotime("$date -" . ($w ? $w - $first : 6) . ' days')); //获取本周开始日期，如果$w是0，则表示周日，减去 6 天
        $now_end = date('Y-m-d', strtotime("$now_start +6 days"));  //本周结束日期
        $data = $this->request->param();
        $res = LeaderDoc::with(['admin', 'unit' => ['community']])->find($data['leader_id']);
        if (is_null($res)) {
            return $this->response(403, '未找到该信息');
        }
        if (empty($res['unit'])) {
            $res['unit_title'] = '未知单位';
            $res['community_title'] = '未知社区';
        } else {
            $res['unit_title'] = $res['unit']['title'];
            $res['community_title'] = $res['unit']['community']['community_title'] ?? '未知社区';
        }
        $res['path_arr'] = json_decode($res['path'], true);
        $res['c_time'] = date('Y-m-d', strtotime($res['create_time']));
        $res['now_time'] = $date;
        $res['now_end'] = $now_end;
        return $this->response($res->toArray());
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/16 15:36
     * @return \think\response\Json
     * 审核领导调度
     */
    public function auditLeader()
    {
        $data = $this->request->param();
        LeaderDoc::update($data);
        AdminLog::record(intval($data['status']) === 2 ? '审核通过领导调度' : '拒绝通过领导调度', $this->request->param('id'), $this->request->uid, $this->request->username);
        return $this->response();
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/16 15:38
     * @param $id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除领导调度
     */
    public function deleteLeader($id)
    {
        $res = LeaderDoc::find($id);
        if (is_null($res)) {
            return $this->response(403, '找不到该资源信息');
        }
        $res->delete();
        AdminLog::record('删除领导调度', $this->request->param(), $this->request->uid, $this->request->username);
        return $this->response();
    }


    /** ==============================包保单位活动登记备案========================================= */


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/11 15:20
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 数据源---登记
     */
    public function getActivityInspect()
    {
        $limit = $this->request->param('limit', 10);
        $type = $this->request->param('type', 0);
        $map = [];
        if (intval($type) === 0) {
            $user = Admins::with(['unit' => ['community']])->find($this->request->wx_id);
            if (!is_null($user['unit']['community'])) {
                //如果不为空
                $ress = GatherCompany::where(['gather_company_title' => $user['unit']['community']['community_title']])->find();
                if (!is_null($ress)) {
                    $admin = Admins::where(['unit_id' => $ress->id])->column('id');
                    if (!in_array($this->request->wx_id, $admin, true)) {
                        array_unshift($admin, $this->request->wx_id);
                    }
                    $map[] = ['user_id', 'in', $admin];
                } else {
                    return $this->response(403, '找不到该资源信息');
                }
            } else {
                $map[] = ['unit_id', '=', $this->request->wx_unit_id];
            }
            $map[] = ['module', '=', $this->request->param('module')];
        }
        $res = PutOnRecord::with(['admin', 'unit' => ['community'], 'inspectActivity' => function ($query) {
            $query->with(['unit' => ['community']])->where(['draft' => 2]);
            return $query;
        }])->where($map)->order('create_time desc')->paginate($limit)->each(function ($item, $key) {
            if (empty($item['unit'])) {
                $item['unit_title'] = '未知单位';
                $item['community_title'] = '未知社区';
            } else {
                $item['unit_title'] = $item['unit']['title'];
                $item['community_title'] = $item['unit']['community']['community_title'] ?? '未知社区';
            }
            if (!empty($item['inspectActivity'])) {

                foreach ($item['inspectActivity'] as $k => $v) {
                    if (empty($v['unit'])) {
                        $item['inspectActivity'][$k]['i_unit_title'] = '未知单位';
                        $item['inspectActivity'][$k]['i_community_title'] = '未知社区';
                    } else {
                        $item['inspectActivity'][$k]['i_unit_title'] = $item['unit']['title'];
                        $item['inspectActivity'][$k]['i_community_title'] = $item['unit']['community']['community_title'] ?? '未知社区';
                    }
                }
            }
            return $item;
        });
        return $this->response($res);
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/3/9 16:13
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 获取所有活动
     */
    public function getActivityAll()
    {
        $limit = $this->request->param('limit', 10);
        $type = $this->request->param('type', 0);
        $draft = $this->request->param('draft', 1);
        $module = $this->request->param('module', 0);
        $map = [];
        if (intval($draft) === 0) {
            $draft_one = 2;
        } else {
            $draft_one = 1;
        }
        if (intval($module) !== 0) {
            $map[] = ['module', '=', $module];
        }
        $map[] = ['draft', '=', $draft_one];
        $res = InspectActivity::with(['admin', 'unit' => ['community'], 'put'])->where($map)->paginate($limit)->each(function ($item, $key) {
            if (empty($item['unit'])) {
                $item['unit_title'] = '未知单位';
                $item['community_title'] = '未知社区';
            } else {
                $item['unit_title'] = $item['unit']['title'];
                $item['community_title'] = $item['unit']['community']['community_title'] ?? '未知社区';
            }
            $item['put_name'] = $item['put']['title'] ?? '未知';
            return $item;
        });
        return $this->response($res);
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/11 13:50
     * @return \think\response\Json
     * 保存活动登记备案
     */
    public function savePutOnRecord()
    {
        $data = $this->request->param();
        $data['user_id'] = $this->request->wx_id;
        $data['username'] = $this->request->wx_user_name;
        $data['unit_id'] = $this->request->wx_unit_id;
        PutOnRecord::create($data);
        //操作日志
        AdminLog::record('保存活动登记备案', $data, $this->request->wx_id, $this->request->wx_user_name);
        return $this->response();
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/17 10:53
     * @param $id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除活动登记备案
     */
    public function deletePutOnRecord($id)
    {
        $res = PutOnRecord::with('inspectActivity')->find($id);
        if (is_null($res)) {
            return $this->response(403, '找不到该资源信息');
        }
        $res->together(['inspectActivity'])->delete();
        AdminLog::record('删除活动登记备案', $this->request->param(), $this->request->uid, $this->request->username);
        return $this->response();
    }




    /** ==============================包保单位活动创建========================================= */


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/14 9:39
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 根据条件获取对应的标签
     */
    public function getActivityTag()
    {
        $type_id = $this->request->param('type_id'); //标签归属
        $activity_id = $this->request->param('activity_id', 0);
        $ly = $this->request->param('ly', 0); //来源
        $map[] = ['currency', '=', InspectActivityTag::IS_CURRENCY_ONE];
        if (intval($ly) === 0) {
            $user_id = $this->request->wx_id;
        } else {
            $user_id = $this->request->param('user_id');
        }
        $map[] = ['user_id', '=', $user_id];

        $map1[] = ['type', '=', $type_id];
        $tag_arr = [];
        if (intval($activity_id) !== 0) {
            $arr = ActivityTagAccess::field('tag_id')->where(['activity_id' => $activity_id])->select()->toArray();
            foreach ($arr as $key => $v) {
                $tag_arr[] = $v['tag_id'];
            }
        }
        $subQuery = InspectActivityTag::whereOr($map)
            ->buildSql();
        $res = Db::table($subQuery . ' a')
            ->where($map1)
            ->order('create_time desc')
            ->select()->each(function ($item, $key) use ($tag_arr) {
                if (count($tag_arr) > 0) {
                    if (in_array($item['id'], $tag_arr)) {
                        $item['isSelected'] = true;
                    } else {
                        $item['isSelected'] = false;
                    }
                } else {
                    $item['isSelected'] = false;
                }
                return $item;
            });
        return $this->response($res);

    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/14 11:42
     * @return \think\response\Json
     * 新增自定义标签
     */
    public function insertTag()
    {
        $data = $this->request->param();
        $data['user_id'] = $this->request->wx_id;
        $id = InspectActivityTag::create($data)->id;
        AdminLog::record('新增自定义标签', $data, $this->request->wx_id, $this->request->wx_user_name);
        return $this->response(['id' => $id]);
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/14 13:57
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 包保单位实地考察活动数据源
     */
    public function getInspectActivityList()
    {
        $limit = $this->request->param('limit', 10);
        $put_id = $this->request->param('put_id', 10);
        $draft = $this->request->param('draft', 1);
        if (intval($draft) === 0) {
            $draft_one = 2;
        } else {
            $draft_one = 1;
        }
        $map[] = ['put_id', '=', $put_id];
        $map[] = ['module', '=', $this->request->param('module', 1)];
        $map[] = ['user_id', '=', $this->request->wx_id];
        $map[] = ['draft', '=', $draft_one];
        $res = InspectActivity::with(['admin', 'unit'])->where($map)->order('create_time desc')->paginate($limit)->each(function ($item, $key) {
            if (empty($item['unit'])) {
                $item['unit_title'] = '未知单位';
            } else {
                $item['unit_title'] = $item['unit']['title'];
            }

            if ($item['path']) {
                $path_arr = json_decode($item['path'], true);
                $item['path_arr'] = reset($path_arr)['url'] ?? Env::get('IMG_HTTP.img_http') . 'logo.png';
            } else {
                $item['path_arr'] = Env::get('IMG_HTTP.img_http') . 'logo.png';
            }
            return $item;

        });
        return $this->response($res);
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/14 13:42
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 包保单位实地考察新增活动
     */
    public function saveActivity()
    {
        $data = $this->request->param();
        $ly = $this->request->param('ly', 0); //来源
        $activity_id = $this->request->param('id', 0);
        if (is_array($data['path'])) {
            foreach ($data['path'] as $key => $v) {
                $data['path'][$key]['thumb'] = $v['url'];
            }
            $data['path'] = json_encode($data['path'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); //不转义
        }
        if (intval($ly) === 0) {
            $data['user_id'] = $this->request->wx_id ?? $this->request->uid;
            $data['username'] = $this->request->wx_user_name ?? $this->request->username;
            $data['unit_id'] = $this->request->wx_unit_id ?? $this->request->unit_id;
        }
//        $putOnRecord = PutOnRecord::find($data['put_id']);
//        if (is_null($putOnRecord)) {
//            return $this->response(404, '当前备案不存在');
//        }
//        $data['project_id'] = $putOnRecord->project_id;
//        $data['project_name'] = $putOnRecord->project_name;

//        if(intval($data['draft']) === 2){
//            $user_id = $this->request->wx_id ?? $this->request->uid;
//            $inspectActivity = InspectActivity::where(['put_id'=>$data['put_id'],'draft'=>2,'module'=>$data['module'],'user_id'=>$user_id])->find();
//
//            if (!is_null($inspectActivity)){
//                return $this->response(404, '该备案下已经存在活动，请勿重复提交！');
//            }
//        }
        if (intval($activity_id) === 0) {
            $activity_id = InspectActivity::create($data)->id;
        } else {
            $activity = InspectActivity::find($activity_id);
            $activity->update($data);
        }
        if (array_key_exists('interestSelected', $data)) {
            //查找标签是否存在  存在删除后再新增
            $res_tag = ActivityTagAccess::where(['activity_id' => $activity_id])->select();
            if (!$res_tag->isEmpty()) {
                $res_tag->delete();
            }

            //标签 ---  处理
            foreach ($data['interestSelected'] as $key => $v) {
                ActivityTagAccess::create([
                    'tag_id' => $v,
                    'activity_id' => $activity_id
                ]);
            }
        }
        //操作日志
        AdminLog::record('包保单位实地考察新增活动', json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), $this->request->wx_id ?? $this->request->uid, $this->request->wx_user_name ?? $this->request->username);
        return $this->response();
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/15 10:24
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 详情
     */
    public function activityDetail()
    {
        $date = date('Y-m-d');  //当前日期
        $first = 1; //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
        $w = date('w', strtotime($date));  //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
        $now_start = date('Y-m-d', strtotime("$date -" . ($w ? $w - $first : 6) . ' days')); //获取本周开始日期，如果$w是0，则表示周日，减去 6 天
        $now_end = date('Y-m-d', strtotime("$now_start +6 days"));  //本周结束日期
        $data = $this->request->param();
        $res = InspectActivity::with(['admin', 'unit' => ['community'], 'put', 'tag'])->find($data['id']);
        if (is_null($res)) {
            return $this->response(403, '未找到该信息');
        }
        if (empty($res['unit'])) {
            $res['unit_title'] = '未知单位';
            $res['community_title'] = '未知社区';
        } else {
            $res['unit_title'] = $res['unit']['title'];
            $res['community_title'] = $res['unit']['community']['community_title'] ?? '未知社区';
        }
        $res['path_arr'] = json_decode($res['path'], true);
        $res['now_end'] = $now_end;
        $res['c_time'] = date('Y-m-d', strtotime($res['create_time']));
        $res['now_time'] = $date;
        return $this->response($res->toArray());
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/17 15:04
     * @return \think\response\Json
     * 实地考察审核
     */
    public function auditActivity()
    {
        $data = $this->request->param();
        InspectActivity::update($data);
        AdminLog::record(intval($data['status']) === 2 ? '审核通过实地考察' : '拒绝通过实地考察', $this->request->param('id'), $this->request->uid, $this->request->username);
        return $this->response();
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/17 15:07
     * @param $id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除考察审核
     */
    public function deleteActivity($id)
    {
        $res = InspectActivity::find($id);
        if (is_null($res)) {
            return $this->response(403, '找不到该资源信息');
        }
        $res->delete();
        AdminLog::record('删除考察审核', $this->request->param(), $this->request->uid, $this->request->username);
        return $this->response();
    }

    /** ===================================宣传劝导======================================== */

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/14 15:57
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 调查问卷数据源
     */
    public function getExamineList()
    {
        $limit = $this->request->param('limit', 10);
        $ly = $this->request->param('ly', 0);
        $draft = $this->request->param('draft', 0);
        if (intval($draft) == 0) {
            $draft_one = 2;
        } else {
            $draft_one = 1;
        }
        $map = [];
        if (intval($ly) === 0) {
            $map[] = ['user_id', '=', $this->request->wx_id];
        }
        $map[] = ['draft', '=', $draft_one];
        $res = Examine::with(['admin', 'unit'])->where($map)->order('create_time desc')->paginate($limit)->each(function ($item, $key) {
            if (empty($item['unit'])) {
                $item['unit_title'] = '未知单位';
                $item['community_title'] = '未知社区';
            } else {
                $item['unit_title'] = $item['unit']['title'];
                $item['community_title'] = $item['unit']['community']['community_title'] ?? '未知社区';
            }

            if ($item['path']) {
                $path_arr = json_decode($item['path'], true);
                $item['path_arr'] = reset($path_arr)['url'] ?? Env::get('IMG_HTTP.img_http') . 'logo.png';
            } else {
                $item['path_arr'] = Env::get('IMG_HTTP.img_http') . 'logo.png';
            }
            return $item;

        });
        return $this->response($res);
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/14 15:53
     * @return \think\response\Json
     * 保存调查问卷
     */
    public function saveExamine()
    {
        $data = $this->request->param();
        $ly = $this->request->param('ly', 0);
        $id = $this->request->param('id', 0);
        if (is_array($data['path'])) {
            foreach ($data['path'] as $key => $v) {
                $data['path'][$key]['thumb'] = $v['url'];
            }
            $data['path'] = json_encode($data['path'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); //不转义
        }
        if (intval($ly) === 0) {
            $data['user_id'] = $this->request->wx_id ?? $this->request->uid;
            $data['username'] = $this->request->wx_user_name ?? $this->request->username;
            $data['unit_id'] = $this->request->wx_unit_id ?? $this->request->unit_id;
        }
        if (intval($id) === 0) {
            Examine::create($data)->id;
        } else {
            $activity = Examine::find($id);
            $activity->update($data);
        }

        //操作日志
        AdminLog::record('包保单位调查问卷', json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), $this->request->wx_id ?? $this->request->uid, $this->request->wx_user_name ?? $this->request->username);
        return $this->response();
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/15 11:00
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 详情
     */
    public function examineDetail()
    {
        $data = $this->request->param();
        $res = Examine::with(['admin', 'unit' => ['community']])->find($data['id']);
        if (is_null($res)) {
            return $this->response(403, '未找到该信息');
        }
        if (empty($res['unit'])) {
            $res['unit_title'] = '未知单位';
            $res['community_title'] = '未知社区';
        } else {
            $res['unit_title'] = $res['unit']['title'];
            $res['community_title'] = $res['unit']['community']['community_title'] ?? '未知社区';
        }
        $res['path_arr'] = json_decode($res['path'], true);
        return $this->response($res->toArray());
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/17 9:15
     * @param $id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除宣传劝导
     */
    public function deleteExamine($id)
    {
        $res = Examine::find($id);
        if (is_null($res)) {
            return $this->response(403, '找不到该资源信息');
        }
        $res->delete();
        AdminLog::record('删除宣传劝导', $this->request->param(), $this->request->uid, $this->request->username);
        return $this->response();
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/17 9:17
     * @return \think\response\Json
     * 宣传劝导审核
     */
    public function auditExamine()
    {
        $data = $this->request->param();
        Examine::update($data);
        AdminLog::record(intval($data['status']) === 2 ? '审核通过宣传劝导' : '拒绝通过宣传劝导', $this->request->param('id'), $this->request->uid, $this->request->username);
        return $this->response();
    }


    /** ===================================特色工作======================================== */


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/14 15:57
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 特色工作数据源
     */
    public function getCharacteristicList()
    {
        $limit = $this->request->param('limit', 10);
        $ly = $this->request->param('ly', 0);
        $draft = $this->request->param('draft', 1);
        if (intval($draft) === 0) {
            $draft_one = 2;
        } else {
            $draft_one = 1;
        }
        $map = [];
        if (intval($ly) === 0) {
            $map[] = ['user_id', '=', $this->request->wx_id];
        }
        $map[] = ['draft', '=', $draft_one];
        $res = Characteristic::with(['admin', 'unit'])->where($map)->order('create_time desc')->paginate($limit)->each(function ($item, $key) {
            if (empty($item['unit'])) {
                $item['unit_title'] = '未知单位';
                $item['community_title'] = '未知社区';
            } else {
                $item['unit_title'] = $item['unit']['title'];
                $item['community_title'] = $item['unit']['community']['community_title'] ?? '未知社区';
            }

            if ($item['path']) {
                $path_arr = json_decode($item['path'], true);
                $item['path_arr'] = reset($path_arr)['url'] ?? Env::get('IMG_HTTP.img_http') . 'logo.png';
            } else {
                $item['path_arr'] = Env::get('IMG_HTTP.img_http') . 'logo.png';
            }
            return $item;

        });
        return $this->response($res);
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/14 15:53
     * @return \think\response\Json
     * 保存特色工作
     */
    public function saveCharacteristic()
    {
        $data = $this->request->param();
        $ly = $this->request->param('ly', 0);
        $id = $this->request->param('id', 0);
        if (is_array($data['path'])) {
            foreach ($data['path'] as $key => $v) {
                $data['path'][$key]['thumb'] = $v['url'];
            }
            $data['path'] = json_encode($data['path'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); //不转义
        }
        if (intval($ly) === 0) {
            $data['user_id'] = $this->request->wx_id ?? $this->request->uid;
            $data['username'] = $this->request->wx_user_name ?? $this->request->username;
            $data['unit_id'] = $this->request->wx_unit_id ?? $this->request->unit_id;
        }
        if (intval($id) === 0) {
            Characteristic::create($data)->id;
        } else {
            $activity = Characteristic::find($id);
            $activity->update($data);
        }

        //操作日志
        AdminLog::record('包保单位保存特色工作', json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), $this->request->wx_id ?? $this->request->uid, $this->request->wx_user_name ?? $this->request->username);
        return $this->response();
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/17 9:28
     * @param $id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除特色工作
     */
    public function deleteCharacteristic($id)
    {
        $res = Characteristic::find($id);
        if (is_null($res)) {
            return $this->response(403, '找不到该资源信息');
        }
        $res->delete();
        AdminLog::record('删除特色工作', $this->request->param(), $this->request->uid, $this->request->username);
        return $this->response();
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/15 11:00
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 详情
     */
    public function characteristicDetail()
    {
        $data = $this->request->param();
        $res = Characteristic::with(['admin', 'unit' => ['community']])->find($data['id']);
        if (is_null($res)) {
            return $this->response(403, '未找到该信息');
        }
        if (empty($res['unit'])) {
            $res['unit_title'] = '未知单位';
            $res['community_title'] = '未知社区';
        } else {
            $res['unit_title'] = $res['unit']['title'];
            $res['community_title'] = $res['unit']['community']['community_title'] ?? '未知社区';
        }
        $res['path_arr'] = json_decode($res['path'], true);
        return $this->response($res->toArray());
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/2/17 9:31
     * @return \think\response\Json
     * 审核特色工作
     */
    public function auditCharacteristic()
    {
        $data = $this->request->param();
        Characteristic::update($data);
        AdminLog::record(intval($data['status']) === 2 ? '审核通过特色工作' : '拒绝通过特色工作', $this->request->param('id'), $this->request->uid, $this->request->username);
        return $this->response();
    }


    /** ===================================临时相册========================================*/

    public function getTemporaryAlbum()
    {
        $limit = $this->request->param('limit', 100);
        $res = TemporaryAlbum::withTrashed()->order('create_time desc')->paginate($limit);
        return $this->response($res);
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/3/10 17:49
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 单位
     */
    public function checkUnit()
    {
        $user = Admins::find($this->request->wx_id);
        if (is_null($user)) {
            return $this->response(403, '未找到用户');
        }
        $res = GatherCompany::where(['id' => $user->unit_id])->find();
        if (is_null($res)) {
            return $this->response(403, '未找到单位');
        }
        $unit = Community::where(['community_title' => $res->gather_company_title])->find();
        if (!is_null($unit)) {
            return $this->response(['is_true' => true]);
        } else {
            return $this->response(['is_true' => false]);
        }
    }



    /** ===================================疑难问题========================================*/

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/3/18 16:36
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * 获取疑难问题
     */
    public function getDifficultList()
    {
        $limit = $this->request->param('limit', 10);
        $ly = $this->request->param('ly', 0);
        $draft = $this->request->param('draft', 0);
        if (intval($draft) == 0) {
            $draft_one = 2;
        } else {
            $draft_one = 1;
        }
        $map = [];
        if (intval($ly) === 0) {
            $map[] = ['user_id', '=', $this->request->wx_id];
        }
        $map[] = ['draft', '=', $draft_one];
        $res = Difficult::with(['admin', 'unit'])->where($map)->order('create_time desc')->paginate($limit)->each(function ($item, $key) {
            if (empty($item['unit'])) {
                $item['unit_title'] = '未知单位';
                $item['community_title'] = '未知社区';
            } else {
                $item['unit_title'] = $item['unit']['title'];
                $item['community_title'] = $item['unit']['community']['community_title'] ?? '未知社区';
            }

            if ($item['path']) {
                $path_arr = json_decode($item['path'], true);
                $item['path_arr'] = reset($path_arr)['url'] ?? Env::get('IMG_HTTP.img_http') . 'logo.png';
            } else {
                $item['path_arr'] = Env::get('IMG_HTTP.img_http') . 'logo.png';
            }
            return $item;

        });
        return $this->response($res);
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/3/18 16:34
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 保存疑难问题
     */
    public function saveDifficult()
    {
        $data = $this->request->param();
        $ly = $this->request->param('ly', 0);
        $id = $this->request->param('id', 0);
        if (is_array($data['path'])) {
            foreach ($data['path'] as $key => $v) {
                $data['path'][$key]['thumb'] = $v['url'];
            }
            $data['path'] = json_encode($data['path'], JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE); //不转义
        }
        if (intval($ly) === 0) {
            $data['user_id'] = $this->request->wx_id ?? $this->request->uid;
            $data['username'] = $this->request->wx_user_name ?? $this->request->username;
            $data['unit_id'] = $this->request->wx_unit_id ?? $this->request->unit_id;
        }
        if (intval($id) === 0) {
            Difficult::create($data)->id;
        } else {
            $activity = Difficult::find($id);
            $activity->update($data);
        }

        //操作日志
        AdminLog::record('保存疑难问题', json_encode($data, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), $this->request->wx_id ?? $this->request->uid, $this->request->wx_user_name ?? $this->request->username);
        return $this->response();
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/3/18 16:42
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 疑难问题详情
     */
    public function difficultDetail()
    {
        $date = date('Y-m-d');  //当前日期
        $first = 1; //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
        $w = date('w', strtotime($date));  //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
        $now_start = date('Y-m-d', strtotime("$date -" . ($w ? $w - $first : 6) . ' days')); //获取本周开始日期，如果$w是0，则表示周日，减去 6 天
        $now_end = date('Y-m-d', strtotime("$now_start +6 days"));  //本周结束日期
        $data = $this->request->param();
        $res = Difficult::with(['admin', 'unit' => ['community']])->find($data['id']);
        if (is_null($res)) {
            return $this->response(403, '未找到该信息');
        }
        if (empty($res['unit'])) {
            $res['unit_title'] = '未知单位';
            $res['community_title'] = '未知社区';
        } else {
            $res['unit_title'] = $res['unit']['title'];
            $res['community_title'] = $res['unit']['community']['community_title'] ?? '未知社区';
        }
        $res['path_arr'] = json_decode($res['path'], true);
        $res['c_time'] = date('Y-m-d', strtotime($res['create_time']));
        $res['now_time'] = $date;
        $res['now_end'] = $now_end;
        return $this->response($res->toArray());
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/3/22 10:04
     * @return \think\response\Json
     * 审核疑难问题
     */
    public function auditDifficult()
    {
        $data = $this->request->param();
        Difficult::update($data);
        AdminLog::record(intval($data['status']) === 2 ? '审核通过疑难问题' : '拒绝通过疑难问题', $this->request->param('id'), $this->request->uid, $this->request->username);
        return $this->response();
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/3/22 10:05
     * @param $id
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 删除疑难问题
     */
    public function deleteDifficult($id)
    {
        $res = Difficult::find($id);
        if (is_null($res)) {
            return $this->response(403, '找不到该资源信息');
        }
        $res->delete();
        AdminLog::record('删除疑难问题', $id, $this->request->uid, $this->request->username);
        return $this->response();
    }

    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/3/22 15:46
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 上传统计
     */
    public function uploadCount()
    {
        $month = $this->request->param('searchMonth');
        if(empty($month)){
            $month = date('Y-m', time());
        }
        $res = GatherCompany::field('id,gather_company_title')->where(['type'=>1])->withCount(['leader'=>function($query) use($month){
            $query->whereMonth('create_time',$month);
            return $query;
        }, 'sceneInspect'=>function($q) use($month){
            $q->whereMonth('create_time',$month);
            return $q;
        },'declareActivity'=>function($q1) use($month){
            $q1->whereMonth('create_time',$month);
            return $q1;
        },'practiceActivity'=>function($q2) use($month){
            $q2->whereMonth('create_time',$month);
            return $q2;
        },'examine'=>function($q3) use($month) {
            $q3->whereMonth('create_time',$month);
            return $q3;
        },'characteristic'=>function($q4) use($month) {
            $q4->whereMonth('create_time',$month);
            return $q4;
        },'difficult'=>function($q5)  use($month){
            $q5->whereMonth('create_time',$month);
            return $q5;
        }])->withCount(['leader' => function ($query2, &$alias2) use($month) {
                //领导调度已审核 并且为正常上传
                $query2->where(['status' => 2,'type'=>1])->whereMonth('create_time',$month);
                $alias2 = 'leader_audited_count';
                return $query2;
            }, 'sceneInspect' => function ($scene, &$scene_alias) use($month) {
                //实地考察已审核
                $scene->where(['status' => 2])->whereMonth('create_time',$month);
                $scene_alias = 'sceneInspect_audited_count';
                return $scene;
            }, 'declareActivity' => function ($scene, &$scene_alias) use($month) {
                //申报活动已审核
                $scene->where(['status' => 2])->whereMonth('create_time',$month);
                $scene_alias = 'declareActivity_audited_count';
                return $scene;
            }, 'practiceActivity' => function ($practice, &$practice_alias) use($month) {
                //实践活动已审核
                $practice->where(['status' => 2])->whereMonth('create_time',$month);
                $practice_alias = 'practiceActivity_audited_count';
                return $practice;
            }, 'examine' => function ($practice, &$practice_alias) use($month) {
                //宣传劝导已审核
                $practice->where(['status' => 2])->whereMonth('create_time',$month);
                $practice_alias = 'examine_audited_count';
                return $practice;
            }, 'characteristic' => function ($practice, &$practice_alias) use($month) {
                //特色工作已审核
                $practice->where(['status' => 2])->whereMonth('create_time',$month);
                $practice_alias = 'characteristic_audited_count';
                return $practice;
            }, 'difficult' => function ($practice, &$practice_alias) use($month) {
                //疑难问题已审核
                $practice->where(['status' => 2])->whereMonth('create_time',$month);
                $practice_alias = 'difficult_audited_count';
                return $practice;
            }])->withCount(['leader' => function ($query2, &$alias2) use($month) {
                //领导调度审核拒绝
                $query2->where(['status' => 3])->whereMonth('create_time',$month);
                $alias2 = 'leader_refuse_count';
                return $query2;
            }, 'sceneInspect' => function ($scene, &$scene_alias) use($month) {
                //实地考察审核拒绝
                $scene->where(['status' => 3])->whereMonth('create_time',$month);
                $scene_alias = 'sceneInspect_refuse_count';
                return $scene;
            },'declareActivity' => function ($scene, &$scene_alias) use($month) {
                //申报活动审核拒绝
                $scene->where(['status' => 3])->whereMonth('create_time',$month);
                $scene_alias = 'declareActivity_refuse_count';
                return $scene;
            }, 'practiceActivity' => function ($scene, &$scene_alias)  use($month){
                //实践活动审核拒绝
                $scene->where(['status' => 3])->whereMonth('create_time',$month);
                $scene_alias = 'practiceActivity_refuse_count';
                return $scene;
            }, 'examine' => function ($practice, &$practice_alias)  use($month) {
                //宣传劝导审核拒绝
                $practice->where(['status' => 3])->whereMonth('create_time',$month);
                $practice_alias = 'examine_refuse_count';
                return $practice;
            }, 'characteristic' => function ($practice, &$practice_alias) use($month) {
                //特色工作审核拒绝
                $practice->where(['status' => 3])->whereMonth('create_time',$month);
                $practice_alias = 'characteristic_refuse_count';
                return $practice;
            }, 'difficult' => function ($practice, &$practice_alias) use($month) {
                //疑难问题审核拒绝
                $practice->where(['status' => 3])->whereMonth('create_time',$month);
                $practice_alias = 'difficult_refuse_count';
                return $practice;
            }])->withCount(['leader' => function ($query2, &$alias2) use($month) {
                //领导调度领导请假
                $query2->where(['type' => 2])->whereMonth('create_time',$month);
                $alias2 = 'leader_leave_count';
                return $query2;
            }])->order('leader_count desc')->select()->each(function ($item,$key){
                $item['percentage'] = round((($item['leader_audited_count'] + $item['sceneInspect_audited_count'] + $item['declareActivity_audited_count'] +$item['practiceActivity_audited_count']+$item['examine_audited_count']) / 13 * 100),2)  .'%';
                return $item;
            })->toArray();
       return $this->response($res);
    }


    /**
     * Notes:
     * User: liuhailong
     * DateTime: 2022/3/23 10:24
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     * 工作成效评价统计
     */
    public function evaluate(){
        $month = $this->request->param('searchMonth');
        if(empty($month)){
            $month = date('Y-m', time());
        }
        $res = GatherCompany::field('id,gather_company_title')->where(['type'=>1])
            ->with(['assess'=>function($q_assess) use($month){ //测评考核
                $q_assess->field('id,assess_value,month_date,unit_id')->where('month_date',$month);
                return $q_assess;
            }])
            ->withAvg(['leader' =>  function ($query, &$alias) use($month) {
                //领导调度已审核 并且为正常上传
                $query->where(['status' => 2,'type'=>1])->whereMonth('create_time',$month);
                $alias = 'leader_avg_count';
                return $query;
            }], 'rate')
            ->withAvg(['sceneInspect' =>  function ($query, &$alias) use($month) {
                //实地考察已审核 并且为正常上传
                $query->where(['status' => 2])->whereMonth('create_time',$month);
                $alias = 'sceneInspect_avg_count';
                return $query;
            }], 'rate')
            ->withAvg(['declareActivity' =>  function ($query, &$alias) use($month) {
                //申报活动已审核 并且为正常上传
                $query->where(['status' => 2])->whereMonth('create_time',$month);
                $alias = 'declareActivity_avg_count';
                return $query;
            }], 'rate')
            ->withAvg(['practiceActivity' =>  function ($query, &$alias) use($month) {
                //实践活动已审核 并且为正常上传
                $query->where(['status' => 2])->whereMonth('create_time',$month);
                $alias = 'practiceActivity_avg_count';
                return $query;
            }], 'rate')
            ->withAvg(['examine' =>  function ($query, &$alias) use($month) {
                //宣传劝导已审核 并且为正常上传
                $query->where(['status' => 2])->whereMonth('create_time',$month);
                $alias = 'examine_avg_count';
                return $query;
            }], 'rate')
            ->withAvg(['characteristic' =>  function ($query, &$alias) use($month) {
                //特色工作已审核 并且为正常上传
                $query->where(['status' => 2])->whereMonth('create_time',$month);
                $alias = 'characteristic_avg_count';
                return $query;
            }], 'rate')
            ->order('leader_avg_count desc')->select()->each(function ($item,$key){
                if (empty($item['assess'])){
                    $item['assess_value_count'] = 0 .'%';
                }else{
                    $item['assess_value_count'] = $item['assess']['assess_value'] .'%';
                }
                $item['is_edit'] = false;
                $item['leader_avg_count'] = round(($item['leader_avg_count']))  .'%';
                $item['sceneInspect_avg_count'] = round(($item['sceneInspect_avg_count']))  .'%';
                $item['declareActivity_avg_count'] = round(($item['declareActivity_avg_count']))  .'%';
                $item['practiceActivity_avg_count'] = round(($item['practiceActivity_avg_count']))  .'%';
                $item['examine_avg_count'] = round(($item['examine_avg_count']))  .'%';
                $item['characteristic_avg_count'] = round(($item['characteristic_avg_count']))  .'%';
                return $item;
            })->toArray();
        return $this->response($res);
    }
}
